package me.exchange.com.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;

public class CallPhpUtil {

    private static final String url="https://haohanapi.qibeiwang.com/planeorder/refundapply";
    private static final String charts="abcdefghijklmnopqrstuvwxyz1234567890";

    /**
     * 退票申请
     * @return
     */
    public static JSONObject cancelOrder(Map<String,String>map,String appkey){
        //根据appid获取appkey
        JsonUtilJackson jsonUtilJackson=new JsonUtilJackson();
        String timestamp = DateUtil.getDateFormate(new Date());
        String nonce =randomNonce();
        map.put("nonce",nonce);
        map.put("sign",sha256_HMAC(map,appkey));
        System.out.println("sign:"+map.get("sign"));
        return new JSONObject(HttpUtil.post(url,jsonUtilJackson.toJson(map)));
    }

    /**
     * sha256_HMAC加密
     * @param map 请求参数
     * @param secret  秘钥
     * @return 加密后字符串
     */
    public static String sha256_HMAC(Map<String,String> map, String secret) {
        String hash = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {

                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            StringBuilder sb = new StringBuilder();
            //拼接请求参数
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key).append("=").append(val).append("&");
                    }
                }
            }
            sb.append("key=").append(secret);
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            System.out.println(sb.toString());
            byte[] bytes = sha256_HMAC.doFinal(sb.toString().getBytes());
            hash = byteArrayToHexString(bytes);
        } catch (Exception e) {
            System.out.println("Error HmacSHA256 ===========" + e.getMessage());
        }
        return hash;
    }

    /**
     * 将加密后的字节数组转换成字符串
     *
     * @param b 字节数组
     * @return 字符串
     */
    public  static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }

    /**
     * 随机nonce参数的值
     * @return 随机32位的字符串
     */
    public static String randomNonce() {
        String nonce = "";
        Random random = new Random();
        for(int i=0; i<32;i++){
            int s = random.nextInt(36)%36 + 1;
            nonce+=charts.charAt(s-1);
        }
        return nonce;
    }

    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        //必填
        map.put("appid","hhd7a4874e39e7a");
        map.put("memberid","9BD1A9BD96D83AD417E4266873E5300D");
        //接口请求参数
        map.put("order_id","54");
        //根据appid获取appkey
        String appkey = "AKIDav0A5kqLHz1uiKhofGdomXHvJWTBsW9e";
        JSONObject json = CallPhpUtil.cancelOrder(map,appkey);
        String msg = json.get("msg").toString();
        System.out.println(json);
        System.out.println("================================================================================");
    }
}
